package edu.ccut.saturn.basecomponent.database.impl.mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnData;

/**
 * 经refactory后生成的新类,作用:针对mysql将生成的主键在SaturnData重新赋值
 * @author zjh
 *
 */
public class MysqlSetPrimaryKeyInSaturnData {
	/**
	 * @author zjh
	 * @param connection 数据库连接对象
	 * @param saturnSQL saturnSQL对象
	 */
	public static void setPrimaryKeyValue(Connection connection,ISaturnSQL saturnSQL){
		if(connection!=null){
			final String LAST_INSERT_ID="SELECT LAST_INSERT_ID()";
			ResultSet resultSet = null;
			Statement statement = null;
			SaturnData saturnData = null;
			IDataInfo dataInfo = null;
			try {
				statement = connection.createStatement();
				resultSet = statement.executeQuery(LAST_INSERT_ID);
				//结果唯一,如果没有,则返回0;
				resultSet.next();
				if(resultSet.getInt(1)!=0){
					saturnData = saturnSQL.getSaturnData();
					dataInfo = saturnData.getSaturnDataInfo();
					for(String key:dataInfo.keySet()){
						IDataItem dataItem = dataInfo.getDataItem(key);
						if("true".equals(dataItem.getIsPrimaryKey())){
							saturnData.set(key,resultSet.getInt(1));
							break;
						}
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally{
				if(statement != null){
					try {
						statement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
